﻿using System;
using System.Web;
using BLWCMS.Core.Business;
using BLWCMS.Core.IBusiness;
using BLWCMS.Core.Models;
using Nancy;
using Nancy.ModelBinding;

namespace BLWCMS.Web.Modules
{
    public class LoginModule:BaseModule
    {
        private readonly ILoginBusiness _loginBusiness;
        private readonly IAdminBusiness _adminBusiness;

        public LoginModule(ILoginBusiness loginBusiness,IAdminBusiness adminBusiness) : base("/")
        {
            _loginBusiness = loginBusiness;
            _adminBusiness = adminBusiness;

            Get["/login"] = p => GetLogin();

            Post["/login"] = p => PostLogin();
        }

        private dynamic GetLogin()
        {
            LoginModel loginModel=new LoginModel
            {
                ReturnUrl = Request.Query["returnUrl"]
            };
            return View["Login", loginModel];
        }

        private dynamic PostLogin()
        {
            LoginModel loginModel = this.Bind<LoginModel>();
            var res = _loginBusiness.LoginIn(loginModel, Session["CheckCode"].ToString());
            try
            {
                AdminModel adminModel = _adminBusiness.GetModel(Convert.ToInt32(res));
                string[] loginedUser = {adminModel.Id.ToString(), adminModel.Nick};
                Session["loginedUser"] = loginedUser;
                return ResCode.N200("登录成功！", loginModel.ReturnUrl);
            }
            catch (Exception e)
            {
                return res;
            }
        }
    }
}